<template>
    <view class="page" :class="{ 'dark-mode': isDarkMode }">
        <!-- 固定头部区域 -->
        <view class="fixed-header">
            <!-- 头部统计卡片 -->
            <view class="statistics-card">
                <view class="total-amount">
                    <text class="label">总送出礼金</text>
                    <text class="amount">¥{{ dashboardData.totalAmount }}</text>
                </view>
                <view class="statistics-grid">
                    <view class="stat-item">
                        <text class="value">{{ dashboardData.totalCount }}</text>
                        <text class="label">送礼次数</text>
                    </view>
                    <view class="stat-item">
                        <text class="value">¥{{ dashboardData.averageAmount }}</text>
                        <text class="label">平均金额</text>
                    </view>
                    <view class="stat-item">
                        <text class="value">¥{{ dashboardData.maxAmount }}</text>
                        <text class="label">最高金额</text>
                    </view>
                    <view class="stat-item">
                        <text class="value">¥{{ dashboardData.minAmount }}</text>
                        <text class="label">最低金额</text>
                    </view>
                </view>
            </view>

            <!-- 搜索框 -->
            <view class="search-box">
                <view class="search-input">
                    <text class="bigfont big-sousuo"></text>
                    <input type="text" v-model="searchKeyword" placeholder="搜索送礼记录" placeholder-class="placeholder"
                        @input="handleSearch" />
                    <text v-if="searchKeyword" class="bigfont big-guanbi clear-icon" @click="clearSearch"></text>
                </view>
            </view>

            <!-- 列表标题 -->
            <view class="list-header">
                <text class="title">礼金记录</text>
                <text class="count" v-if="searchKeyword">找到 {{ total }} 条记录</text>
            </view>
        </view>

        <!-- 可滚动的列表区域 -->
        <scroll-view class="gift-list" scroll-y @scrolltolower="loadMore" :show-scrollbar="false"
            :refresher-enabled="true" :refresher-triggered="refresherTriggered" @refresherpulling="onPulling"
            @refresherrefresh="onRefresh" @refresherrestore="onRestore" @refresherabort="onAbort" :enhanced="true"
            :bounces="true" :fast-deceleration="true">
            <!-- 空状态显示 -->
            <view v-if="displayRecords.length === 0" class="empty-state">
                <text class="bigfont">&#xe64b;</text>
                <view class="text">还没有礼金记录，快去记录一笔吧</view>
            </view>
            <!-- 列表内容 -->
            <template v-else>
                <view v-for="(item, index) in displayRecords" :key="item.id || index" class="gift-item"
                    :class="{ 'expanded': expandedItems[index] }">
                    <view class="gift-info">
                        <view class="gift-header">
                            <text class="occasion">{{ item.title }}</text>
                            <text class="amount" :class="{ 'negative': item.amount && item.amount < 0 }">¥{{
                                formatAmount(item.amount) }}</text>
                        </view>
                        <view class="gift-details">
                            <text class="date">{{ formatDate(item.date) }}</text>
                            <view v-if="item.notes || item.remark" class="remark-wrapper"
                                @click.stop="toggleExpand(index)">
                                <text class="remark" :class="{ 'expanded': expandedItems[index] }">{{ item.notes ||
                                    item.remark }}</text>
                                <text class="bigfont big-youjiantoucu" v-if="isRemarkLong(item.notes || item.remark)" />
                            </view>
                            <!-- <view v-if="item.location" class="location"> -->
                            <!-- <text class="bigfont big-location"></text> -->
                            <!-- <text>{{ item.location }}</text> -->
                            <!-- </view> -->
                        </view>
                    </view>
                </view>
                <view v-if="loading" class="loading">加载中...</view>
                <view v-else-if="finished" class="list-bottom">
                    没有更多数据了
                </view>
            </template>
        </scroll-view>
    </view>
</template>

<script setup lang="ts">
import { getDashboardData, listByPage, type GiftRecord } from '@/api/todo';
import { isDarkMode } from '@/store/theme';
import { computed, onMounted, ref } from 'vue';

// 格式化日期
const formatDate = (dateStr: string) => {
    const date = new Date(dateStr);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}年${month}月${day}日`;
};

// 格式化金额
const formatAmount = (amount?: number) => {
    if (amount === undefined || amount === null) return '0.00';
    return amount.toFixed(2);
};

// 统计数据接口
interface DashboardData {
    totalAmount: string;
    totalCount: number;
    averageAmount: string;
    maxAmount: string;
    minAmount: string;
}

// 统计数据
const dashboardData = ref<DashboardData>({
    totalAmount: '0.00',
    totalCount: 0,
    averageAmount: '0.00',
    maxAmount: '0.00',
    minAmount: '0.00'
});

// 获取统计数据
const fetchDashboardData = async () => {
    try {
        const { data } = await getDashboardData();
        if (data) {
            dashboardData.value = {
                totalAmount: formatAmount(data.totalAmount),
                totalCount: data.totalCount || 0,
                averageAmount: formatAmount(data.averageAmount),
                maxAmount: formatAmount(data.maxAmount),
                minAmount: formatAmount(data.minAmount)
            };
        }
    } catch (error) {
        console.error('获取统计数据失败:', error);
    }
};

// 礼金记录数据
const giftRecords = ref<GiftRecord[]>([]);
const total = ref(0);
const pageNum = ref(1);
const pageSize = ref(10);
const loading = ref(false);
const finished = ref(false);

// 获取礼金记录
const fetchGiftRecords = async (isRefresh = false) => {
    if (loading.value || (finished.value && !isRefresh)) return;

    try {
        loading.value = true;
        const query = {
            pageNum: isRefresh ? 1 : pageNum.value,
            pageSize: pageSize.value,
            title: searchKeyword.value
        };

        const response = await listByPage(query);

        if (response.data) {
            const { records, totalRow } = response.data;
            if (isRefresh) {
                giftRecords.value = records;
                pageNum.value = 1;
            } else {
                giftRecords.value.push(...records);
            }
            total.value = totalRow;
            finished.value = giftRecords.value.length >= totalRow;
            pageNum.value++;
        }
    } catch (error) {
        console.error('获取礼金记录失败:', error);
    } finally {
        loading.value = false;
    }
};

// 搜索关键词
const searchKeyword = ref('');

// 搜索处理
const handleSearch = () => {
    fetchGiftRecords(true);
};

// 展示的记录
const displayRecords = computed(() => giftRecords.value);

// 加载更多
const loadMore = async () => {
    await fetchGiftRecords();
};

// 展开状态管理
const expandedItems = ref<{ [key: number]: boolean }>({});

// 切换展开状态
const toggleExpand = (index: number) => {
    const item = displayRecords.value[index];
    const remark = item.notes || item.remark;
    if (!isRemarkLong(remark)) return;
    expandedItems.value[index] = !expandedItems.value[index];
};

// 判断备注是否超过一行
const isRemarkLong = (remark?: string) => {
    return remark && remark.length > 20;
};

// 下拉刷新相关
const refresherTriggered = ref(false);

const onPulling = () => {
    // 下拉中
};

const onRefresh = async () => {
    refresherTriggered.value = true;
    finished.value = false;
    try {
        await Promise.all([
            fetchDashboardData(),
            fetchGiftRecords(true)
        ]);
    } finally {
        refresherTriggered.value = false;
    }
};

const onRestore = () => {
    // 刷新复位
    refresherTriggered.value = false;
};

const onAbort = () => {
    // 刷新被中止
    refresherTriggered.value = false;
};

// 页面加载时获取数据
onMounted(() => {
    fetchDashboardData();
    fetchGiftRecords();
});

// 清空搜索
const clearSearch = () => {
    searchKeyword.value = '';
    fetchGiftRecords(true);
};
</script>

<style scoped>
.page {
    min-height: 100vh;
    height: 100vh;
    background-color: var(--theme-background);
    position: fixed;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    overflow: hidden;
}

.fixed-header {
    position: relative;
    z-index: 100;
    padding: 32rpx;
    padding-top: calc(var(--status-bar-height) + 44rpx);
    padding-bottom: 24rpx;
}

.statistics-card {
    background: #ffffff;
    border-radius: 16rpx;
    padding: 24rpx;
    margin-bottom: 16rpx;
    box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
}

.total-amount {
    text-align: center;
    margin-bottom: 24rpx;
}

.total-amount .label {
    font-size: 24rpx;
    color: #666;
    margin-bottom: 4rpx;
    display: block;
}

.total-amount .amount {
    font-size: 48rpx;
    font-weight: 600;
    color: #333;
}

.statistics-grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 16rpx;
    padding-top: 24rpx;
    border-top: 2rpx solid #f0f0f0;
}

.stat-item {
    text-align: center;
    padding: 16rpx;
    background: rgba(0, 0, 0, 0.02);
    border-radius: 12rpx;
}

.stat-item .value {
    font-size: 28rpx;
    font-weight: 600;
    color: #333;
    display: block;
    margin-bottom: 8rpx;
    word-break: break-all;
}

.stat-item .label {
    font-size: 22rpx;
    color: #666;
}

.search-box {
    margin-bottom: 16rpx;
}

.search-input {
    background: #ffffff;
    border-radius: 16rpx;
    padding: 20rpx 32rpx;
    display: flex;
    align-items: center;
    gap: 16rpx;
    box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
    position: relative;
}

.search-input .bigfont {
    font-size: 32rpx;
    color: #999;
}

.search-input input {
    flex: 1;
    height: 44rpx;
    font-size: 28rpx;
    color: #333;
    padding-right: 40rpx;
    /* 为清除按钮留出空间 */
}

.placeholder {
    color: #999;
    font-size: 28rpx;
}

.list-header {
    padding: 0 16rpx;
    /* margin-bottom: 24rpx; */
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.list-header .title {
    font-size: 32rpx;
    font-weight: 600;
    color: #333;
}

.list-header .count {
    font-size: 24rpx;
    color: #999;
}

.gift-list {
    padding: 32rpx;
    padding-top: 16rpx;
    padding-bottom: 0;
    box-sizing: border-box;
    -webkit-overflow-scrolling: touch;
    scroll-behavior: smooth;
    overscroll-behavior: contain;
    position: relative;
    height: calc(100vh - var(--status-bar-height) - 480rpx);
    overflow-y: auto;
}

.gift-item {
    background: #ffffff;
    border-radius: 16rpx;
    padding: 24rpx;
    margin-bottom: 24rpx;
    box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
    transition: all 0.3s ease;
    transform: translateZ(0);
    -webkit-transform: translateZ(0);
    will-change: transform;
    backface-visibility: hidden;
    -webkit-backface-visibility: hidden;
}

.gift-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 12rpx;
}

.gift-details {
    display: flex;
    flex-direction: column;
    gap: 8rpx;
}

.gift-info .occasion {
    font-size: 28rpx;
    color: #333;
}

.gift-info .date {
    font-size: 24rpx;
    color: #999;
}

.remark-wrapper {
    position: relative;
    background-color: rgba(64, 158, 255, 0.05);
    padding: 16rpx 24rpx;
    padding-right: 64rpx;
    border-radius: 8rpx;
    margin-top: 8rpx;
    cursor: pointer;
    max-width: 100%;
    box-sizing: border-box;
    display: flex;
    align-items: center;
    border: 1px solid rgba(64, 158, 255, 0.1);
}

.gift-info .remark {
    font-size: 24rpx;
    color: var(--theme-color, #409EFF);
    line-height: 1.4;
    flex: 1;
    min-width: 0;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    transition: all 0.3s ease;
    opacity: 0.8;
}

.gift-info .remark.expanded {
    white-space: normal;
    text-overflow: clip;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 5;
}

.big-youjiantoucu {
    position: absolute;
    right: 16rpx;
    top: 50%;
    transform: translateY(-50%);
    font-size: 24rpx;
    color: var(--theme-color, #409EFF);
    transition: transform 0.3s ease;
    width: 32rpx;
    height: 32rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    opacity: 0.8;
}

.expanded .big-youjiantoucu {
    transform: translateY(-50%) rotate(90deg);
}

.gift-item .amount {
    font-size: 32rpx;
    font-weight: 600;
    color: #333;
}

.gift-item .amount.negative {
    color: #ff4d4f;
}

/* 暗黑模式样式 */
.dark-mode {
    background-color: #121212;
}

.dark-mode .fixed-header {
    background-color: #121212;
}

.dark-mode .statistics-card,
.dark-mode .search-input,
.dark-mode .gift-item {
    background: #1e1e1e;
    border: 2rpx solid rgba(255, 255, 255, 0.1);
    box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.3);
}

.dark-mode .total-amount .amount,
.dark-mode .stat-item .value,
.dark-mode .list-header .title,
.dark-mode .gift-info .occasion,
.dark-mode .gift-item .amount {
    color: rgba(255, 255, 255, 0.9);
}

.dark-mode .total-amount .label,
.dark-mode .stat-item .label,
.dark-mode .gift-info .date,
.dark-mode .gift-info .remark {
    color: rgba(255, 255, 255, 0.6);
}

.dark-mode .statistics-grid {
    border-color: rgba(255, 255, 255, 0.1);
}

.dark-mode .gift-item .amount.negative {
    color: #ff7875;
}

.dark-mode .search-input input {
    color: rgba(255, 255, 255, 0.9);
}

.dark-mode .search-input .bigfont {
    color: rgba(255, 255, 255, 0.6);
}

.dark-mode .placeholder {
    color: rgba(255, 255, 255, 0.4);
}

.dark-mode .list-header .count {
    color: rgba(255, 255, 255, 0.6);
}

.dark-mode .remark-wrapper {
    background-color: rgba(64, 158, 255, 0.1);
    border: 1px solid rgba(64, 158, 255, 0.15);
}

.dark-mode .gift-info .remark {
    color: var(--theme-color, #409EFF);
    opacity: 0.9;
}

.dark-mode .big-youjiantoucu {
    color: var(--theme-color, #409EFF);
    opacity: 0.9;
}

.empty-state {
    text-align: center;
    padding: 120rpx 32rpx;
    color: #999;
}

.empty-state .bigfont {
    font-size: 96rpx;
    color: #ddd;
    margin-bottom: 24rpx;
}

.empty-state .text {
    font-size: 28rpx;
}

/* 暗黑模式样式 */
.dark-mode .empty-state .bigfont {
    color: rgba(255, 255, 255, 0.1);
}

.dark-mode .empty-state .text {
    color: rgba(255, 255, 255, 0.45);
}

.loading {
    text-align: center;
    padding: 32rpx;
    color: #999;
    font-size: 24rpx;
}

.list-bottom {
    text-align: center;
    padding: 32rpx;
    color: #999;
    font-size: 24rpx;
    padding-bottom: calc(env(safe-area-inset-bottom) + 100px);
}

.location {
    display: flex;
    align-items: center;
    gap: 8rpx;
    font-size: 24rpx;
    color: #999;
    margin-top: 8rpx;
}

.location .bigfont {
    font-size: 24rpx;
}

/* 暗黑模式样式 */
.dark-mode .stat-item {
    background: rgba(255, 255, 255, 0.05);
}

.search-input .clear-icon {
    position: absolute;
    right: 32rpx;
    top: 50%;
    transform: translateY(-50%);
    font-size: 32rpx;
    color: #999;
    padding: 10rpx;
    z-index: 2;
    width: 32rpx;
    height: 32rpx;
    display: flex;
    align-items: center;
    justify-content: center;
}

.dark-mode .search-input .clear-icon {
    color: rgba(255, 255, 255, 0.6);
}
</style>